package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"path/filepath"
	"short-lang/cache"
	"short-lang/models"
	"strconv"
	"time"
)

func Upload(c *gin.Context) {
	file, err := c.FormFile("img")
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "文件获取失败",
		})
		return
	}
	if file.Size > 2*1024*1024 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "文件大小不能超过2mb",
		})
		return
	}
	book := map[string]bool{
		".png":  true,
		".jpeg": true,
		".jpg":  true,
	}
	ext := filepath.Ext(file.Filename)
	if !book[ext] {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "文件格式不正确",
		})
		return
	}
	path := "/static/img" + file.Filename
	err = c.SaveUploadedFile(file, path)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "文件更新失败",
		})
		return
	}
	url := "http://" + c.Request.Host + "/" + path
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "照片上传成功",
		"data": url,
	})
	return
}

func List(c *gin.Context) {
	var list []models.Article
	redis_key := "article_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": list,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var detail models.Article
	redis_key := "article_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).First(&detail)
		jsonData, _ := json.Marshal(detail)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &detail)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": detail,
	})
	return
}

func Like(c *gin.Context) {
	userId, _ := strconv.Atoi(c.PostForm("user_id"))
	articleId, _ := strconv.Atoi(c.PostForm("article_id"))
	var like models.Like
	err := models.DB.Where("userId=? and article=?", userId, articleId).First(&like).Error
	if err == nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能重复点赞",
		})
		return
	}
	tex := models.DB.Begin()
	data := models.Like{
		UserId:    userId,
		ArticleId: articleId,
	}
	err = tex.Create(&data).Error
	if err != nil {
		tex.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "点赞失败",
		})
		return
	}
	var article models.Article
	err = tex.Where("id=?", articleId).First(&article).Error
	if err != nil {
		tex.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "文章不存在",
		})
		return
	}
	article.LikeCount++
	err = tex.Save(&article).Error
	if err != nil {
		tex.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "点赞失败",
		})
		return
	}
	tex.Commit()
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "点赞成功",
	})
	return
}
